<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
class Suppliers extends Model
{

    // 表名
    protected $name = 'kuyou_suppliers';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->page($page,$limit)->field("id,supplyer_code,supplyertype_id,first_connect_name,first_connect_mobile,first_connect_phone,qq_wx_email,connect_address,note,supplyer_name,opening_payable,opening_prepayment,need_give_account,identification,deposit_bank,bank_number,first_connect_mobile,FROM_UNIXTIME(account_time,'%Y-%m-%d') as account_time,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime,status")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->field("id,supplyer_code,supplyertype_id,first_connect_name,first_connect_mobile,first_connect_phone,qq_wx_email,connect_address,note,supplyer_name,opening_payable,opening_prepayment,need_give_account,identification,deposit_bank,bank_number,first_connect_mobile,FROM_UNIXTIME(account_time,'%Y-%m-%d') as account_time,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime,status")->select())->toArray();
        }
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['supplyertype_name'] = (new Supplyertype())->where(['id'=>$list_v['supplyertype_id']])->value('supplier_type_name');
            $list[$list_k]['status'] = (int)$list_v['status'];
        }

        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public static function getDetail($id){
        $detail = self::where(function ($query) use ($id) {
            $query->where('id', '=', $id);
        })->field("id,supplyer_code,supplyertype_id,first_connect_name,first_connect_mobile,first_connect_phone,qq_wx_email,connect_address,note,supplyer_name,opening_payable,opening_prepayment,identification,deposit_bank,bank_number,first_connect_mobile,FROM_UNIXTIME(account_time,'%Y-%m-%d') as account_time,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime,status")->find();
        if($detail){
            $detail['supplyertype_name'] = (new Supplyertype())->where(['id'=>$detail['supplyertype_id']])->value('supplier_type_name');
            $detail['user'] = collection((new SuppliersUser())->where(['sid'=>$detail['id']])->field("first_connect_name,first_connect_mobile,first_connect_phone,qq_wx_email,connect_address,is_first")->select())->toArray();
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
        return ['status'=>200,'msg'=>$detail];
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'supplyer_code|编号'=>'require',
                'supplyer_name|名称'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['supplyer_code'],2);//验证编号是否合法
                if($status){
                    if(isset($detail['account_time']) && !empty($detail['account_time'])){
                        $detail['account_time'] = strtotime($detail['account_time']);
                    }else{
                        $detail['account_time'] = time();
                    }
                    if(isset($detail['supplyertype_id']) && !empty($detail['supplyertype_id'])){
                        $supplyertype_id = (new Supplyertype())->where(['id'=>$detail['supplyertype_id']])->value('id');
                        if(empty($supplyertype_id)){
                            return ['status'=>500,'msg'=>'供应商类别不存在'];
                        }
                    }
                    $user = (array)json_decode($detail['user'], true);
                    $default = '';
                    foreach ($user as $user_k=>$user_v){
                        if(!is_array($user_v)){
                            return ['status'=>500,'msg'=>'联系人数据格式错误'];
                        }
                        if(isset($user_v['first_connect_name']) && !empty($user_v['first_connect_name']) && isset($user_v['first_connect_mobile']) && !empty($user_v['first_connect_mobile'])){
                            if($user_v['is_first']==1 && $default!==''){
                                return ['status'=>500,'msg'=>'只能选择一个首要联系人'];
                            }
                            if($user_v['is_first']==1){
                                $default = $user_k;
                            }
                        }else{
                            unset($user[$user_k]);
                        }
                    }
                    $default = $default===''?0:$default;
                    $user[$default]['is_first'] = 1;
                    $detail['first_connect_name'] = $user[$default]['first_connect_name'];
                    $detail['first_connect_mobile'] = isset($user[$default]['first_connect_mobile'])?$user[$default]['first_connect_mobile']:'';
                    $detail['first_connect_phone'] = isset($user[$default]['first_connect_phone'])?$user[$default]['first_connect_phone']:'';
                    $detail['qq_wx_email'] = isset($user[$default]['qq_wx_email'])?$user[$default]['qq_wx_email']:'';
                    $detail['connect_address'] = isset($user[$default]['connect_address'])?$user[$default]['connect_address']:'';
                    $detail['need_give_account'] = round(((float)$detail['opening_payable']-(float)$detail['opening_prepayment']),4);

                    $model = new Suppliers();
                    $row = $model->where(['supplyer_code'=>$detail['supplyer_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'编号已存在'];
                    }
                    $res = false;
                    Db::startTrans();
                    try {
                        $res = $model->allowField(true)->save($detail);
                        $result = $model->id;

                        //插入联系人
                        foreach ($user as $user_k=>$user_v){
                            $user[$user_k]['supplyer_code'] = trim($detail['supplyer_code']);
                            $user[$user_k]['sid'] = $result;
                        }
                        (new SuppliersUser())->allowField(true)->saveAll($user);

                        //插入期初应付/预付
                        $detail['need_give_account'] = ((float)$detail['opening_payable']-(float)$detail['opening_prepayment']);
                        $business_type = 5;
                        if($detail['need_give_account']>0){//应付
                            (new WriteoffSource())->allowField(true)->save([
                                'purchase_type' => 5,
                                'type' => 3,
                                'suppliers_code' => $detail['supplyer_code'],
                                'purchase_code' => $detail['supplyer_code'],
                                'purchase_time' => $detail['account_time'],
                                'price' => $detail['need_give_account'],
                                'write_off' => $detail['need_give_account'],
                                'remark' => $detail['note'],
                            ]);
                        }else if($detail['need_give_account']<0){//预付
                            (new WriteoffSource())->allowField(true)->save([
                                'purchase_type' => 6,
                                'type' => 3,
                                'suppliers_code' => $detail['supplyer_code'],
                                'purchase_code' => $detail['supplyer_code'],
                                'purchase_time' => $detail['account_time'],
                                'price' => -$detail['need_give_account'],
                                'write_off' => -$detail['need_give_account'],
                                'remark' => $detail['note'],
                            ]);
                            $business_type = 6;
                        }
                        (new PaymentLog())->allowField(true)->save([
                            'suppliers_code' => $detail['supplyer_code'],
                            'business_type' => $business_type,
                            'bill_time' => $detail['account_time'],
                            'bill_code' => $detail['supplyer_code'],
                            'give_money' => $detail['need_give_account'],
                        ]);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($res){
                        return ['status'=>200,'msg'=>$result];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $type = isset($detail['type'])?$detail['type']:1;
            $type = $type==1?1:2;
            if($type==1){
                $check = (new Commons())->checkParameter($detail,[
                    'id|ID'=>'require|number',
                    'supplyer_code|编号'=>'require',
                    'supplyer_name|名称'=>'require',
                ]);
                if(isset($check['status'])){
                    return $check;
                }else{
                    $status = (new Commons())->checkCode($detail['supplyer_code'],2);//验证编号是否合法
                    if($status){
                        if(isset($detail['account_time']) && !empty($detail['account_time'])){
                            $detail['account_time'] = strtotime($detail['account_time']);
                        }else{
                            $detail['account_time'] = time();
                        }
                        if(isset($detail['supplyertype_id']) && !empty($detail['supplyertype_id'])){
                            $supplyertype_id = (new Supplyertype())->where(['id'=>$detail['supplyertype_id']])->value('id');
                            if(empty($supplyertype_id)){
                                return ['status'=>500,'msg'=>'供应商类别不存在'];
                            }
                        }
                        $user = (array)json_decode($detail['user'], true);
                        $default = '';
                        foreach ($user as $user_k=>$user_v){
                            if(!is_array($user_v)){
                                return ['status'=>500,'msg'=>'联系人数据格式错误'];
                            }
                            if(isset($user_v['first_connect_name']) && !empty($user_v['first_connect_name']) && isset($user_v['first_connect_mobile']) && !empty($user_v['first_connect_mobile'])){
                                if($user_v['is_first']==1 && $default!==''){
                                    return ['status'=>500,'msg'=>'只能选择一个首要联系人'];
                                }
                                if($user_v['is_first']==1){
                                    $default = $user_k;
                                }
                            }else{
                                unset($user[$user_k]);
                            }
                        }
                        $default = $default===''?0:$default;
                        $user[$default]['is_first'] = 1;
                        $detail['first_connect_name'] = $user[$default]['first_connect_name'];
                        $detail['first_connect_mobile'] = isset($user[$default]['first_connect_mobile'])?$user[$default]['first_connect_mobile']:'';
                        $detail['first_connect_phone'] = isset($user[$default]['first_connect_phone'])?$user[$default]['first_connect_phone']:'';
                        $detail['qq_wx_email'] = isset($user[$default]['qq_wx_email'])?$user[$default]['qq_wx_email']:'';
                        $detail['connect_address'] = isset($user[$default]['connect_address'])?$user[$default]['connect_address']:'';
                        $detail['need_give_account'] = round(((float)$detail['opening_payable']-(float)$detail['opening_prepayment']),4);

                        $model = new Suppliers();
                        $row = $model->where(['supplyer_code'=>$detail['supplyer_code'],'id'=>['<>',$detail['id']]])->value('id');
                        if($row){
                            return ['status'=>500,'msg'=>'编号已存在'];
                        }

                        $WriteoffSource = Db::name('kuyou_writeoff_source')->where(['suppliers_code'=>$row['supplyer_code'],'type'=>3])->value('price');
                        if(((float)$row['opening_payable']-(float)$row['opening_prepayment'])==$WriteoffSource && ((float)$row['opening_payable']-(float)$row['opening_prepayment'])!=((float)$detail['opening_payable']-(float)$detail['opening_prepayment'])){
                            $order = Db::name('kuyou_writeoff')->where(['suppliers_id|suppliers_out_id|suppliers_enter_id'=>$row['id']])->find();
                            if($order){
                                return ['status'=>400,'msg'=>'已关联核销单，不可编辑金额'];
                            }
                        }

                        $row = $model->get($detail['id']);
                        if($row){
                            $ids = $row['id'];
                            $res = false;
                            Db::startTrans();
                            try {
                                (new SuppliersUser())->where(['sid'=>$ids])->delete();

                                $res = $row->allowField(true)->save($detail);

                                //插入联系人
                                foreach ($user as $user_k=>$user_v){
                                    $user[$user_k]['supplyer_code'] = trim($detail['supplyer_code']);
                                    $user[$user_k]['sid'] = $ids;
                                }
                                (new SuppliersUser())->allowField(true)->saveAll($user);

                                //插入期初应付/预付
                                //插入期初应付/预付
                                $WriteoffSource = Db::name('kuyou_writeoff_source')->where(['suppliers_code'=>$row['supplyer_code'],'type'=>3])->find();
                                $PaymentLog = Db::name('kuyou_payment_log')->where(['bill_code'=>$row['supplyer_code'],'business_type'=>['in',[5,6]]])->find();
                                $detail['need_give_account'] = ((float)$detail['opening_payable']-(float)$detail['opening_prepayment']);
                                if($WriteoffSource){
                                    $business_type = 5;
                                    if($detail['need_give_account']>0){//应付
                                        Db::name('kuyou_writeoff_source')->where(['id'=>$WriteoffSource['id']])->update([
                                            'suppliers_code' => $detail['supplyer_code'],
                                            'purchase_code' => $detail['supplyer_code'],
                                            'purchase_time' => $detail['account_time'],
                                            'price' => $detail['need_give_account'],
                                            'write_off' => $detail['need_give_account'],
                                            'remark' => $detail['note'],
                                        ]);
                                    }else if($detail['need_give_account']<0){//预付
                                        Db::name('kuyou_writeoff_source')->where(['id'=>$WriteoffSource['id']])->update([
                                            'suppliers_code' => $detail['supplyer_code'],
                                            'purchase_code' => $detail['supplyer_code'],
                                            'purchase_time' => $detail['account_time'],
                                            'price' => -$detail['need_give_account'],
                                            'write_off' => -$detail['need_give_account'],
                                            'remark' => $detail['note'],
                                        ]);
                                        $business_type = 6;
                                    }
                                    Db::name('kuyou_payment_log')->where(['id'=>$PaymentLog['id']])->update([
                                        'suppliers_code' => $detail['supplyer_code'],
                                        'business_type' => $business_type,
                                        'bill_time' => $detail['account_time'],
                                        'bill_code' => $detail['supplyer_code'],
                                        'give_money' => $detail['need_give_account'],
                                    ]);
                                }else{
                                    $business_type = 5;
                                    if($detail['need_give_account']>0){//应付
                                        Db::name('kuyou_writeoff_source')->insert([
                                            'purchase_type' => 5,
                                            'type' => 3,
                                            'suppliers_code' => $detail['supplyer_code'],
                                            'purchase_code' => $detail['supplyer_code'],
                                            'purchase_time' => $detail['account_time'],
                                            'price' => $detail['need_give_account'],
                                            'write_off' => $detail['need_give_account'],
                                            'remark' => $detail['note'],
                                        ]);
                                    }else if($detail['need_give_account']<0){//预付
                                        Db::name('kuyou_writeoff_source')->insert([
                                            'purchase_type' => 6,
                                            'type' => 3,
                                            'suppliers_code' => $detail['supplyer_code'],
                                            'purchase_code' => $detail['supplyer_code'],
                                            'purchase_time' => $detail['account_time'],
                                            'price' => -$detail['need_give_account'],
                                            'write_off' => -$detail['need_give_account'],
                                            'remark' => $detail['note'],
                                        ]);
                                        $business_type = 6;
                                    }
                                    Db::name('kuyou_payment_log')->insert([
                                        'suppliers_code' => $detail['supplyer_code'],
                                        'business_type' => $business_type,
                                        'bill_time' => $detail['account_time'],
                                        'bill_code' => $detail['supplyer_code'],
                                        'give_money' => $detail['need_give_account'],
                                    ]);
                                }

                                Db::commit();
                            } catch (Exception $e) {
                                Db::rollback();
                                return ['status'=>500,'msg'=>$e->getMessage()];
                            }
                            if($res){
                                return ['status'=>200,'msg'=>'更新成功'];
                            }else{
                                return ['status'=>500,'msg'=>'更新失败'];
                            }
                        }else{
                            return ['status'=>500,'msg'=>'未查询到可更新数据'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'编号规则错误'];
                    }
                }
            }else{
                $check = (new Commons())->checkParameter($detail,[
                    'id|ID'=>'require|number',
                    'status|状态'=>'require',
                ]);
                if(isset($check['status'])){
                    return $check;
                }else{
                    $model = new Suppliers();
                    $row = $model->where(['id'=>$detail['id']])->value('id');
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'供应商不存在'];
                    }else{
                        $res = false;
                        Db::startTrans();
                        try {
                            $res = $model->where(['id'=>$detail['id']])->update(['status'=>$detail['status']]);
                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }
                }
            }
        }
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $ids = (new Suppliers())->where(['id'=>['in',$id]])->field('id,supplyer_code')->select();
            $code = [];
            foreach ($ids as $k=>$v){
                $code[] = $v['supplyer_code'];
                $suppliers = self::getDetail($v['id']);
                $suppliers_name = isset($suppliers['supplyer_name'])?$suppliers['supplyer_name']:'供应商';
                $order_info = (new GoodsPurchaseOrder())->where(['supplyer_code'=>$v['supplyer_code']])->field('id')->find();
                if(!empty($order_info)){
                    return ['status'=>500,'msg'=>$suppliers_name.'已有购货订单，不可删除'];
                }
                $order_info = (new GoodsPurchaseInfo())->where(['supplyer_code'=>$v['supplyer_code']])->field('id')->find();
                if(!empty($order_info)){
                    return ['status'=>500,'msg'=>$suppliers_name.'已有购货单，不可删除'];
                }
                $order_info = (new GoodsExchangeInfo())->where(['supplyer_code'=>$v['supplyer_code']])->field('id')->find();
                if(!empty($order_info)){
                    return ['status'=>500,'msg'=>$suppliers_name.'已有购货退货单，不可删除'];
                }
                $order_info = (new Warehousing())->where(['suppliers_id'=>$v['id']])->field('id')->find();
                if(!empty($order_info)){
                    return ['status'=>500,'msg'=>$suppliers_name.'已有其他入库单，不可删除'];
                }
                $order_info = (new Writeoff())->where(['suppliers_id|suppliers_out_id|suppliers_enter_id'=>$v['id']])->field('id')->find();
                if(!empty($order_info)){
                    return ['status'=>500,'msg'=>$suppliers_name.'已有核销单，不可删除'];
                }
            }
            Db::startTrans();
            try {
                $res = (new Suppliers())->where(['id'=>['in',$id]])->delete();
                (new SuppliersUser())->where(['supplyer_code'=>['in',$code]])->delete();
                (new WriteoffSource())->where(['suppliers_code'=>['in',$code],'type'=>3])->delete();
                (new PaymentLog())->where(['bill_code'=>['in',$code],'business_type'=>['in',[5,6]]])->delete();
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$res];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 导入
     * @param array $add,$edit
     * @return array
     */
    public static function import($add,$edit){
        if(empty($add) && empty($edit)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $model = new Suppliers();

            Db::startTrans();
            try {
                foreach ($add as $add_k=>$detail){
                    $res = $model->allowField(true)->save($detail);
                    $result = $model->id;

                    $user = $detail['userlist'];
                    //插入联系人
                    foreach ($user as $user_k=>$user_v){
                        $user[$user_k]['supplyer_code'] = trim($detail['supplyer_code']);
                        $user[$user_k]['sid'] = $result;
                    }
                    (new SuppliersUser())->allowField(true)->saveAll($user);

                    //插入期初应付/预付
                    $business_type = 5;
                    if($detail['need_give_account']>0){//应付
                        (new WriteoffSource())->allowField(true)->save([
                            'purchase_type' => 5,
                            'type' => 3,
                            'suppliers_code' => $detail['supplyer_code'],
                            'purchase_code' => $detail['supplyer_code'],
                            'purchase_time' => $detail['account_time'],
                            'price' => $detail['need_give_account'],
                            'write_off' => $detail['need_give_account'],
                            'remark' => $detail['note'],
                        ]);
                    }else if($detail['need_give_account']<0){//预付
                        (new WriteoffSource())->allowField(true)->save([
                            'purchase_type' => 6,
                            'type' => 3,
                            'suppliers_code' => $detail['supplyer_code'],
                            'purchase_code' => $detail['supplyer_code'],
                            'purchase_time' => $detail['account_time'],
                            'price' => $detail['need_give_account'],
                            'write_off' => $detail['need_give_account'],
                            'remark' => $detail['note'],
                        ]);
                        $business_type = 6;
                    }
                    (new PaymentLog())->allowField(true)->save([
                        'suppliers_code' => $detail['supplyer_code'],
                        'business_type' => $business_type,
                        'bill_time' => $detail['account_time'],
                        'bill_code' => $detail['supplyer_code'],
                        'give_money' => $detail['need_give_account'],
                    ]);
                }
                foreach ($edit as $edit_k=>$detail){
                    $row = $model->get($detail['id']);
                    $ids = $detail['id'];
                    (new SuppliersUser())->where(['sid'=>$ids])->delete();
                    (new WriteoffSource())->where(['suppliers_code'=>$row['supplyer_code'],'type'=>3])->delete();
                    (new PaymentLog())->where(['bill_code'=>$row['supplyer_code'],'business_type'=>['in',[5,6]]])->delete();

                    $res = $row->allowField(true)->save($detail);

                    $user = $detail['userlist'];
                    //插入联系人
                    foreach ($user as $user_k=>$user_v){
                        $user[$user_k]['supplyer_code'] = trim($detail['supplyer_code']);
                        $user[$user_k]['sid'] = $ids;
                    }
                    (new SuppliersUser())->allowField(true)->saveAll($user);

                    //插入期初应付/预付
                    $business_type = 5;
                    if($detail['need_give_account']>0){//应付
                        (new WriteoffSource())->allowField(true)->save([
                            'purchase_type' => 5,
                            'type' => 3,
                            'suppliers_code' => $detail['supplyer_code'],
                            'purchase_code' => $detail['supplyer_code'],
                            'purchase_time' => $detail['account_time'],
                            'price' => $detail['need_give_account'],
                            'write_off' => $detail['need_give_account'],
                            'remark' => $detail['note'],
                        ]);
                    }else if($detail['need_give_account']<0){//预付
                        (new WriteoffSource())->allowField(true)->save([
                            'purchase_type' => 6,
                            'type' => 3,
                            'suppliers_code' => $detail['supplyer_code'],
                            'purchase_code' => $detail['supplyer_code'],
                            'purchase_time' => $detail['account_time'],
                            'price' => $detail['need_give_account'],
                            'write_off' => $detail['need_give_account'],
                            'remark' => $detail['note'],
                        ]);
                        $business_type = 6;
                    }
                    (new PaymentLog())->allowField(true)->save([
                        'suppliers_code' => $detail['supplyer_code'],
                        'business_type' => $business_type,
                        'bill_time' => $detail['account_time'],
                        'bill_code' => $detail['supplyer_code'],
                        'give_money' => $detail['need_give_account'],
                    ]);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            return ['status'=>200,'msg'=>'导入成功'];
        }
    }
}
